// 发送端
// 通过监听串口消息，将指令分发不同接收端,通过esp-now一对多发送

#include <Arduino.h>
#include "espNow.hpp"

typedef struct
{
  int rece_esp8266;
  int rece_esp32c3;
} Servo;

Servo servo_stru;

SemaphoreHandle_t xMutexData = NULL; //创建信号量Handler
TickType_t timeOut = 1000;           //用于获取信号量的Timeout 1000 ticks

// 取数据赋值
void readCmdTask(void *pvParam)
{

  while (1)
  {
    //获取串口数据
    if (Serial.available() > 0)
    {
      char serialData = Serial.read();
      if (serialData == 'A')
      {
        //检查key并赋值
        if (xSemaphoreTake(xMutexData, timeOut) == pdPASS)
        {
          int angle_tmp = Serial.parseInt();
          servo_stru.rece_esp8266 = angle_tmp;
          xSemaphoreGive(xMutexData); //释放钥匙
          Serial.println("A" + angle_tmp);
        }
      }
      else if (serialData == 'F')
      {
        //检查key并赋值
        if (xSemaphoreTake(xMutexData, timeOut) == pdPASS)
        {
          int angle_tmp = Serial.parseInt();
          servo_stru.rece_esp32c3 = angle_tmp;
          xSemaphoreGive(xMutexData); //释放钥匙
          Serial.println("F" + angle_tmp);
        }
      }
    }

    vTaskDelay(2);
  }
}

// 分发执行，发送端将消息通过esp-now发送至接收端
void runCmdTask(void *ptParam)
{
  espBegin();
  servo_stru.rece_esp32c3 = 0;
  servo_stru.rece_esp32c3 = 0;

  while (1)
  {

    if (xSemaphoreTake(xMutexData, timeOut) == pdPASS)
    {

      // 分发数据
      espSend((uint8_t *)&servo_stru, 0);
      //释放钥匙
      xSemaphoreGive(xMutexData);
    }

    vTaskDelay(200);
  }
}

void setup()
{
  Serial.begin(9600);

  xMutexData = xSemaphoreCreateMutex(); //创建MUTEX

  xTaskCreate(readCmdTask, "readCmd", 1024 * 8, NULL, 1, NULL);
  vTaskDelay(1000); //让readCmd提前先运行一秒获取第一笔数据
  xTaskCreate(runCmdTask, "runCmd", 1024 * 8, NULL, 1, NULL);
}

void loop()
{
  vTaskDelay(1000);
}
